package com.itheima.interceptor;

import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        log.info("uri = {}", uri);

        if (uri.contains("login")) {
            return true;
        }
        String token=request.getHeader("token");
        if (token==null) {
            log.warn("令牌不存在");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        try {
            Claims claims = JwtUtils.parseJWT(token);
        }catch (Exception e) {
            log.error("令牌解析失败:{}", e.getMessage());
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        return true;

    }
}
